package com.lr.transfer.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @Auther liran
 * @Date 2018/9/30 09:56
 * @Description
 */
@Slf4j
public class FormatImageUtil {

    public static final String JPG = "jpg";
    public static final String GIF = "gif";
    public static final String PNG = "png";
    public static final String BMP = "bmp";

    public static void main(String[] args) {
        String src = "E:/2.png";
        System.out.println(conversionPngToJpg(src));
        //System.out.println(createImageLogo(src, "liran"));
        //conversionCore(PNG, JPG, src, null);//JPG转成PNG
        //conversionCore(JPG, GIF, src);//JPG转成GIF
        //conversionCore(JPG, BMP, src);//JPG转成BMP
        //其余格式转化只要调用Conversion函数即可

    }

    /**
     * 方法描述: png --> jpg
     *
     * @return boolean
     * @param: [filePath 文件路径地址]
     * @author liran
     * @date 2018/9/30 11:12
     */
    public static boolean conversionPngToJpg(String filePath) {
        String suffix = getFileSuffix(filePath);
        if (StringUtils.equals(PNG, suffix)) {
            String noSuffixPath = StringUtils.substringBeforeLast(filePath, PNG);
            return conversionCore(PNG, JPG, noSuffixPath, null);
        }
        log.info("图片格式有误 方法期望格式:{},输入的格式:{}", PNG, suffix);
        return false;
    }

    /**
     * 获取文件后缀名 不包含点
     */
    public static String getFileSuffix(String fileWholeName) {
        if (ToolUtil.isEmpty(fileWholeName)) {
            log.info("未获取到图片后缀名，图片源路径：{}", fileWholeName);
            return "none";
        }
        int lastIndexOf = fileWholeName.lastIndexOf(".");
        return fileWholeName.substring(lastIndexOf + 1);
    }

    /**
     * 方法描述: inputFormat表示原格式，outputFormat表示转化后的格式  src表示源文件路径, outPath 自定义文件路径
     * 注意路径里不要包括 文件后缀名
     * 正例如：E:/2.
     * 反例：E:/2.jpg
     *
     * @return boolean
     * @param: [inputFormat, outputFormat, src]
     * @author liran
     * @date 2018/9/30 10:57
     */
    public static boolean conversionCore(String inputFormat, String outputFormat, String src, String outPath) {
        try {
            File input = new File(src + inputFormat);
            BufferedImage bim = ImageIO.read(input);
            FileOutputStream output;
            if (StringUtils.isNotBlank(outPath)) {
                output = new FileOutputStream(outPath + outputFormat);
            } else {
                output = new FileOutputStream(src + outputFormat);
            }
            return ImageIO.write(bim, outputFormat, output);
        } catch (IOException e) {
            log.error("图片转换异常参数信息 inputFormat：{} outputFormat：{} src：{} outPath：{}  ", inputFormat, outputFormat, src, outPath);
            log.error("图片转换异常：{}", e);
        }
        return false;
    }

    public static boolean createImageLogo(String filePath, String logoText) {
        String suffix = getFileSuffix(filePath);
        if (StringUtils.equals(PNG, suffix) || StringUtils.equals(JPG, suffix) || StringUtils.equals(GIF, suffix) || StringUtils.equals(BMP, suffix)) {
            return markImageByText(logoText, filePath, filePath, 0, Color.BLUE, suffix);
        }
        return false;
    }


    /**
     * 给图片添加水印文字、可设置水印文字的旋转角度
     *
     * @param logoText      要写入的文字
     * @param srcImgPath    源图片路径
     * @param newImagePath  新图片路径
     * @param degree        旋转角度
     * @param color         字体颜色
     * @param imgSuffixName 图片后缀
     */
    public static boolean markImageByText(String logoText, String srcImgPath, String newImagePath, Integer degree, Color color, String imgSuffixName) {
        InputStream is = null;
        OutputStream os = null;
        try {
            // 1、源图片
            java.awt.Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // 2、得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 3、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), java.awt.Image.SCALE_SMOOTH), 0, 0, null);
            // 4、设置水印旋转
            if (null != degree) g.rotate(Math.toRadians(degree), buffImg.getWidth() / 3, buffImg.getHeight() / 3);
            // 5、设置水印文字颜色
            g.setColor(color);
            // 6、设置水印文字Font
            g.setFont(new java.awt.Font(Font.MONOSPACED, java.awt.Font.BOLD, buffImg.getHeight() / 5));
            // 7、设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.25f));
            // 8、第一参数->设置的内容，后面两个参数->文字在图片上的坐标位置(x,y)
            g.drawString(logoText, buffImg.getWidth() / 2, buffImg.getHeight() / 2);
            // 9、释放资源
            g.dispose();
            // 10、生成图片
            os = new FileOutputStream(newImagePath);
            return ImageIO.write(buffImg, imgSuffixName, os);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("图片添加水印错误：{}", e);
        } finally {
            try {
                if (null != is)
                    is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }


}
